﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Abp.Auditing;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Localization;
using Abp.Logging;
using Abp.Runtime.Validation;
using Abp.Timing;
using SimpleCmsWithAbp.EntityFrameworkCore;
using SimpleCmsWithAbp.VerifyCodes;

namespace SimpleCmsWithAbp.Models.TokenAuth
{
    public class AuthenticateModel : ICustomValidate
    {
        [Required]
        [StringLength(AbpUserBase.MaxEmailAddressLength)]
        public string UserNameOrEmailAddress { get; set; }

        [Required]
        [StringLength(AbpUserBase.MaxPlainPasswordLength)]
        public string Password { get; set; }
        
        [Required]
        [StringLength(6)]
        public string VerifyCode { get; set; }

        [Required]
        [StringLength(32)]
        public  string Key { get; set; }

        public bool RememberClient { get; set; }

        public void AddValidationErrors(CustomValidationContext context)
        {
            var verifyCodeRepository =  context.IocResolver.Resolve<IRepository<VerifyCode, long>>();
            var localizationManager = context.IocResolver.Resolve<ILocalizationManager>();
            var record = verifyCodeRepository.FirstOrDefault(m =>m.Md5Key == Key.ToUpper());
            if (record == null || (record.Code.ToUpper() != VerifyCode.ToUpper() || record.Expired < Clock.Now))
            {
                context.Results.Add(new ValidationResult(
                    localizationManager.GetString(SimpleCmsWithAbpConsts.LocalizationSourceName, "verifyCodeInvalid"),
                    new List<string>() {"VerifyCode"}));
            }
            else
            {
                verifyCodeRepository.Delete(record);
            }
        }
    }
}
